import { debounce } from 'lodash-es'
import { ref } from 'vue'
import { useAccountStore } from '@/store/account'
import { usePopupMessageStore } from '@/store/popup-message'
import { $t } from '@/i18n'
import { useYup } from '@/plugins/yup'
import { trackEvent } from '@/gtm'
import API from '@/http'

export function useLogin(onLogin) {
  const { open: openMessage } = usePopupMessageStore()
  const { login } = useAccountStore()

  const credential = ref({
    username: '',
    password: '',
  })

  const errors = ref({
    username: '',
    password: '',
  })

  const check = ref({ username: false, password: false })

  const yup = useYup()
  const schemaUsername = yup.string().required()
  const schemaPassword = yup.string().required()

  const loginDisabled = ref(false)
  const onLoginClicked = debounce(
    () => {
      loginDisabled.value = true
      const v1 = schemaUsername
        .validate(credential.value.username)
        .then((res) => {
          errors.value.username = ''
          check.value.username = true
        })
        .catch((err) => {
          check.value.username = false
          errors.value.username = err
        })

      const v2 = schemaPassword
        .validate(credential.value.password)
        .then((res) => {
          errors.value.password = ''
          check.value.password = true
        })
        .catch((err) => {
          check.value.password = false
          errors.value.password = err
        })

      Promise.all([v1, v2])
        .then(() => {
          if (!check.value.username || !check.value.password) return
          API.Auth.login({
            data: {
              account: credential.value.username,
              password: credential.value.password,
            },
          })
            .then((data) => {
              login(data)
              openMessage($t('message.loginSuccess'))
              trackEvent({ key: 39 })
              onLogin?.()
            })
            .catch((e) => {
              console.error(e)
              openMessage(e.message, true)
            })
        })
        .finally(() => {
          loginDisabled.value = false
        })
    },
    2000,
    { leading: true, trailing: false },
  )

  return {
    credential,
    errors,
    loginDisabled,
    onLoginClicked,
  }
}
